//
//  PictureViewController.m
//  XiangMuB
//
//  Created by 999999999999 on 16/8/14.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "PictureViewController.h"
#import "UIView+BSFrame.h"
#import "Content.h"
#import <MJRefresh.h>
#import <AFNetworking+RXHeader.h>
#import "URL_HeaderDefine.h"
#import "PictureModel.h"
#import "PictireViewCell.h"

@interface PictureViewController ()
@property (nonatomic,strong)NSMutableArray *dataArray;
//当前页码
@property (nonatomic,assign)NSInteger page;
//当加载下一页数据时需要这个参数
@property(nonatomic,strong)NSString *maxtime;
//上一次请求的参数
@property (nonatomic,strong)NSDictionary *params;
@end

@implementation PictureViewController

-(NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTable];
    //先刷新控件在处理数据
    [self setUpRefresh];
    //注册
   [self.tableView registerNib:[UINib nibWithNibName:@"PictireViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];

}
#pragma mark----初始化tableview
-(void)setUpTable{
    //  设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top =TitlesViewY +TitlesViewH;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    //设置滚动条内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    //分割线
    self.tableView.separatorStyle = UITableViewRowAnimationNone;
    self.tableView.backgroundColor = [UIColor clearColor];
}
#pragma mark----刷新数据
-(void)setUpRefresh{
    //下拉刷新,在主线程结束刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    //    根据拖拽比例自动改变透明度
    self.tableView.header.autoChangeAlpha = YES;
    //进入页面自动刷新
    [self.tableView.mj_header beginRefreshing];
    //下拉刷新,加载更多数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
    //    self.tableView.footer.hidden = YES;
    //    [self loadNewTopics];
}
#pragma mark ---数据处理
//在家新的帖子数据
-(void)loadNewTopics{
    
    [self.tableView.mj_footer endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @"10";
    self.params = params;
    
    __weak typeof(self) weakSelf = self;
    [[AFHTTPSessionManager manager]GET:TOPIC_url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"-=-=%@", responseObject);
                if (self.params != params)return;
        // 存储maxtime(maxtime为加载下一页时使用)
        self.maxtime = responseObject[@"info"][@"maxtime"];
        //解析
        for (NSDictionary *dic  in responseObject[@"list"]) {
//                        NSLog(@"%@",dic);
            PictureModel *model = [[PictureModel alloc]init];
            //            NSLog(@"%@",model);
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
        }
        //        NSLog(@"%@",self.dataArray);
        

        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
    }];
}
//加载更多的帖子数据
-(void)loadMoreTopics{
    //    NSLog(@"======%s",__func__);
    [self.tableView.mj_header endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @"10";
    NSInteger page = self.page + 1;
    //页码
    params[@"page"] = @(page);
    params[@"maxtime"]=self.maxtime;
    self.params = params;
    
    __weak typeof(self) weakSelf = self;
    [[AFHTTPSessionManager manager]GET:TOPIC_url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (self.params != params)return;
        // 存储maxtime(maxtime为加载下一页时使用)
        self.maxtime = responseObject[@"info"][@"maxtime"];
       //解析
        for (NSDictionary *dic  in responseObject[@"list"]) {
//                        NSLog(@"%@",dic);
            PictureModel *model = [[PictureModel alloc]init];
            //            NSLog(@"%@",model);
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
        }
        //        NSLog(@"%@",self.dataArray);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            weakSelf.page++;
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.params != params)return;
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
    }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PictireViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[PictireViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    PictureModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PictureModel *model = self.dataArray[indexPath.row];
    CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width -40, MAXFLOAT);
    CGFloat textH = [model.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.height;
    
    //显示图片宽度
    CGFloat pictureW =maxSize.width;
    //显示图片高度
    CGFloat pictureH = pictureW *model.height / model.width;
    if (pictureH >= PICTUREMAXHEIGHT ) {//图片高度过长
        pictureH = PICTUREMAXBREAKHEIGHT;
        model.bigPicture = YES; //大图
    }
    CGFloat pictureY= 10 +textH + 10;
    model.pictureFrame = CGRectMake(10, pictureY, pictureW, pictureH).size.height;
    return 68 + textH + 10+10 +10 + pictureH +20;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
